package com.tarena.lbs.basic.web.filter;

import com.alibaba.nacos.api.utils.StringUtils;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
//@Component
public class UserFilter implements Filter {
    //@Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("我是springMvc过滤器-入口");
        UserPrinciple userPrinciple =null;
        if (servletRequest instanceof HttpServletRequest){
            HttpServletRequest request =(HttpServletRequest) servletRequest;
            String jwt = request.getHeader("Authorization");
            if (!StringUtils.isEmpty(jwt)){
                try {
                    userPrinciple= jwtEncoder.getLoginFromToken(jwt, UserPrinciple.class);
                } catch (BusinessException e) {
                    log.error("解析Token失败");
                }
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
        log.info("我是springMvc过滤器-出口");
    }

}
